package com.david.zhufengfm.utils;

/**
 * Created by sdw on 2015/10/12.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;

/**
 * IO流的工具类
 */
public class StreamUtil {
    private StreamUtil(){}

    public static void close(Object stream){
        if (stream != null) {
            try {
            if(stream instanceof InputStream){

                    ((InputStream) stream).close();
                }else if(stream instanceof OutputStream){
                    ((OutputStream) stream).close();
            }else if (stream instanceof Reader){
                    ((Reader) stream).close();
            }else if(stream instanceof Writer){
                    ((Writer) stream).close();
            }else if(stream instanceof HttpURLConnection){
                ((HttpURLConnection) stream).disconnect();
            }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] readStream(InputStream in) throws IOException {
        byte[] ret=null;
        
        if (in != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[]buffer=new byte[128];
            int len;

            while((len=in.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            //注意：buffer必须要进行=null的操作
            //减少内存溢出的可能性
            buffer=null;
            ret=bos.toByteArray();
            bos.close();;
        }
        return ret;
    }
}
